import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 从 localStorage 获取 token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    const { response } = error
    let message = t('error.networkError')
    
    if (response) {
      switch (response.status) {
        case 401:
          message = t('error.unauthorized')
          // 可以在这里处理未授权的情况，比如跳转到登录页
          break
        case 403:
          message = t('error.forbidden')
          break
        case 404:
          message = t('error.notFound')
          break
        case 500:
          message = t('error.serverError')
          break
        default:
          message = response.data?.message || t('error.unknownError')
      }
    }
    
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default instance 